package thread;

public class Main2
{

    public static void main(String[] args) throws InterruptedException
    {
//        System.out.println("thread.Main Thread Started");
//        Thread t1 = new Thread(new CalcRunnable("A"));
//        Thread t2 = new Thread(new CalcRunnable("B"));
//        t1.start();
//        t2.start();
//        t1.join();
//        System.out.println("thread.Main Thread End");

        //ABC
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        PrintThread at = new PrintThread("A", c, a);
        PrintThread bt = new PrintThread("B", a, b);
        PrintThread ct = new PrintThread("C", b, c);
        at.start();
        Thread.sleep(100);
        bt.start();
        Thread.sleep(100);
        ct.start();

    }

    /***
     * 一个对象的同步方法如果正在某个线程中执行，则其他线程不能进入该对象的任何一个同步方法中
     */
    static class SynC
    {
        public synchronized void pr()
        {
            System.out.println("正在同步");
            try
            {
                Thread.sleep(3000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        public synchronized void pr2()
        {
            System.out.println("第二个正在同步");
        }
    }

    static class CalcRunnable implements Runnable
    {

        CalcRunnable(String msg)
        {
            name = msg;
        }

        private String name;

        @Override
        public void run()
        {
            for (int i = 0; i < 6; i++)
            {
                System.out.println(name + " : " + i);
                try
                {
                    Thread.sleep((long) (Math.random() * 10));
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    static class PrintThread extends Thread
    {
        private String name;
        private Object prev, self;

        public PrintThread(String name, Object prev,Object oj2)
        {
            this.name = name;
            this.prev = prev;
            this.self = oj2;
        }

        @Override
        public void run()
        {
            //ca ab bc
            for (int i = 0; i < 10; i++)
            {
                synchronized (prev)
                {
                    synchronized (self)
                    {
                        System.out.print(name);
                        self.notify();
                    }
                    try
                    {
                        prev.wait();
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
